import React, { Component } from 'react';
import axios from 'axios';
import cookie from 'react-cookies';
import 'katex/dist/katex.min.css';
import { BlockMath } from 'react-katex';
import TheDateTime from '../comm/theDateTime';
import './main.css';
import MenuHead from '../comm/menuHead';
import Table from '../comm/table';

class Math extends Component {
    state = {
        type: "eq",
        expr: " ",
        unns: [],
        ansr: " ",
        ansr_text: " ",
        float: " ",
        curt_tag: "ansr",
        cur_tab: "calc",
        error: "",
        query_expr: "",
        query_unns: "",
        query_latex: "",
        query_text: "",
        query_float: "",
        query_begin_time: "",
        query_end_time: "",
        thead: [
            {en: 'expr', ch: '式子'},
            {en: 'unns', ch: '求解变量'},
            {en: 'latex', ch: 'LaTeX'},
            {en: 'text', ch: 'src'},
            {en: 'float', ch: '近似值'},
            {en: 'create_time', ch: '操作时间'},
        ],
        tdata: [],
        data_queried: [],
        record_count: 0,
        record_hits: 0,
        scroll_id: "",
        restart_query: false,
    }
    handleChange = (e) => {
        this.setState({
            expr: e.target.value
        })
    }
    parseX = (e) => {
        let unns = e.target.value.match(/\b\w+\b/g);
        this.setState({
            unns: unns
        })
    }
    calc = () => {
        let userName = cookie.load('login-name');
        let loginID = cookie.load('login-id');
        axios.post("/app/" + this.state.type + "_calc", {
            "expr": this.state.expr,
            "unns": this.state.unns,
            "userName": userName,
            "loginID": loginID,
        }).then((res) => {
            let curt_tag = "" === res.data.error ? "ansr" : "error";
            this.setState({
                ansr: res.data.latex,
                float: res.data.float,
                ansr_text: res.data.text,
                error: res.data.error,
                curt_tag: curt_tag,
                restart_query: true,
            })
        }).catch((err) => {
            alert(err)
        })
    }
    switchTag = (id) => {
        this.setState({
            curt_tag: id,
        })
    }
    SelectOpr = (e) => {
        this.setState({
            type: e.target.value,
        })
    }
    switchTab = (id) => {
      this.setState({
          cur_tab: id,
      })
    }
    set_query_expr = (e) => {
      this.setState({
        query_expr: e.target.value,
        restart_query: true,
      })
    }
    set_query_unns = (e) => {
      this.setState({
        query_unns: e.target.value,
        restart_query: true,
      })
    }
    set_query_latex = (e) => {
      this.setState({
        query_latex: e.target.value,
        restart_query: true,
      })
    }
    set_query_text = (e) => {
      this.setState({
        query_text: e.target.value,
        restart_query: true,
      })
    }
    set_query_float = (e) => {
      this.setState({
        query_float: e.target.value,
        restart_query: true,
      })
    }
    set_begin_time = (data) => {
        this.setState({
          query_begin_time: data,
          restart_query: true,
        })
    }
    set_end_time = (data) => {
        this.setState({
          query_end_time: data,
          restart_query: true,
        })
    }
    queryCalcRecord = (from, page) => {
        if(!this.state.restart_query && from < this.state.record_hits) {
            let r_data_show = this.state.data_queried.slice(from, from + page);
            this.setState({
                tdata: r_data_show,
            });
            return;
        }
        let userName = cookie.load('login-name');
        let loginID = cookie.load('login-id');
        userName = userName === undefined ? "" : userName;
        loginID = loginID === undefined ? "" : loginID;
        let quer_scroll_id = this.state.scroll_id;
        if(this.state.restart_query){
          from = 0;
          page = 10;
          quer_scroll_id = "";
        }
        let query_unns = this.state.query_unns.match(/\b\w+\b/g);
        if (null === query_unns) {
            query_unns = [];
        }
        axios.post("/app/queryEqCalcRecords", {
            "expr": this.state.query_expr,
            "unns": query_unns,
            "latex": this.state.query_latex,
            "text": this.state.query_text,
            "float": this.state.query_float,
            "time": [this.state.query_begin_time, this.state.query_end_time],
            "size": 1000,
            "scroll_time": "1m",
            "scroll_id": quer_scroll_id,
            "userName": userName,
            "loginID": loginID,
        }).then((res) => {
            if("请先登录" === res.data.error) {
                this.props.history.push('/login');
            }
            let r_data = null === res.data.data ? [] : res.data.data;
            let r_data_queried = [...this.state.data_queried];
            let r_record_hits = this.state.record_hits;
            if(this.state.restart_query){
                r_data_queried = [];
                r_record_hits = 0;
            }
            r_data_queried.push(...r_data);
            let r_data_show = r_data_queried.slice(from, from + page);
            this.setState({
                tdata: r_data_show,
                data_queried: r_data_queried,
                record_count: res.data.count,
                record_hits: r_record_hits + res.data.data.length,
                scroll_id: res.data.scroll_id,
                restart_query: false,
            })
        }).catch((err) => {
            this.setState({error: "请求服务器端时产生的错误信息: " + err});
        })
    }
    batchDelCalcRecord = (records) => {
        let userName = cookie.load('login-name');
        let loginID = cookie.load('login-id');
        userName = userName === undefined ? "" : userName;
        loginID = loginID === undefined ? "" : loginID;
        axios.post("/app/delEqCalcRecords", {
            "record": records,
            "userName": userName,
            "loginID": loginID,
        }).then((res) => {
            if("请先登录" === res.data.error) {
                this.props.history.push('/login');
            } else if ("" !== res.data.error) {
                alert(res.data.error);
            }
            this.setState({
                restart_query: true,
            })
            setTimeout(() => {
                this.queryCalcRecord(0, 10);
              }, 1000);
        }).catch((err) => {
            this.setState({error: "请求服务器端时产生的错误信息: " + err});
        })
    }
    modifyCalcRecord = (data) => {
        this.setState({
            expr: data.expr,
            unns: data.unns,
            ansr: data.latex,
            ansr_text: data.text,
            float: data.float,
            curt_tag: "ansr",
            cur_tab: "calc",
        })
    }
    render(){
        let isCalcShow = this.state.cur_tab === "calc" ? "block" : "none";
        let isQueryShow = this.state.cur_tab === "query" ? "block" : "none";
    
        let calcStyle = this.state.cur_tab === "calc" ? "#99d9ea" : "#f7f7f7";
        let queryStyle = this.state.cur_tab === "query" ? "#99d9ea" : "#f7f7f7";

        let isLatexShow = this.state.curt_tag === "ansr" ? "block" : "none";
        let isFloatShow = this.state.curt_tag === "float" ? "block" : "none";
        let isSrcShow = this.state.curt_tag === "latex_text" ? "block" : "none";
        let isTextShow = this.state.curt_tag === "sympy_text" ? "block" : "none";
        let isErrorShow = this.state.curt_tag === "error" ? "block" : "none";

        let calc_type = this.state.type === "eq" ? "解：" : "计 算";
        let isEq = this.state.type === "eq" ? "block" : "none";

        let latexStyle = this.state.curt_tag === "ansr" ? "#99d9ea" : "#f7f7f7";
        let floatStyle = this.state.curt_tag === "float" ? "#99d9ea" : "#f7f7f7";
        let srcStyle = this.state.curt_tag === "latex_text" ? "#99d9ea" : "#f7f7f7";
        let textStyle = this.state.curt_tag === "sympy_text" ? "#99d9ea" : "#f7f7f7";
        return (
            <div align='center'>
                <MenuHead/>
                <table>
                <tbody>
                <tr>
                    <td>
                    <select onChange={this.SelectOpr}>
                        <option value="eq" defaultValue="selected">解方程</option>
                        <option value="calc">极限</option>
                        <option value="calc">积分</option>
                        <option value="calc">微分</option>
                        <option value="calc">求和</option>
                    </select>
                    </td>
                    <td width='5'></td>
                    <td><span style={{background: `${calcStyle}`}} onClick={() => this.switchTab("calc")}>计算</span></td>
                    <td width='5'></td>
                    <td><span style={{background: `${queryStyle}`}} onClick={() => this.switchTab("query")}>历史查询</span></td>
                    <td width='100'></td>
                </tr>
                </tbody>
                </table>
                <div style={{display: `${isCalcShow}`}}>
                <div>
                    <textarea rows='8' cols='40' id='expr' onChange={this.handleChange} value={this.state.expr}></textarea>
                    <BlockMath math={this.state.expr} errorColor={'#cc0000'} />
                </div>
                <div>
                <table>
                <tbody>
                <tr>
                    <td><div style={{display: `${isEq}`}}>求解变量:</div></td>
                    <td>
                        <div style={{display: `${isEq}`}}>
                            <input type="text" onChange={this.parseX} size="5" maxLength="12" value={this.state.unns}></input>
                        </div>
                    </td>
                    <td width='10'></td>
                    <td><button onClick={this.calc}>{calc_type}</button></td>
                </tr>
                </tbody>
                </table>
                </div>
                <div style={{display: `${isErrorShow}`}}>
                    <br/><span><font color="#FF0000">{this.state.error}</font></span><br/>
                </div>
                <div>
                    <br/>
                    <table>
                    <tbody>
                    <tr>
                        <td><span style={{background: `${latexStyle}`}} onClick={() => this.switchTag("ansr")}>结果</span></td>
                        <td width='5'></td>
                        <td><span style={{background: `${floatStyle}`}} onClick={() => this.switchTag("float")}>近似值</span></td>
                        <td width='5'></td>
                        <td><span style={{background: `${srcStyle}`}} onClick={() => this.switchTag("latex_text")}>LaTeX</span></td>
                        <td width='5'></td>
                        <td><span style={{background: `${textStyle}`}} onClick={() => this.switchTag("sympy_text")}>src</span></td>
                    </tr>
                    </tbody>
                    </table>
                </div>
                <div style={{display: `${isLatexShow}`}}>
                    <BlockMath math={this.state.ansr} errorColor={'#cc0000'} />
                </div>
                <div style={{display: `${isFloatShow}`}}>
                    <textarea rows='8' cols='40' value={this.state.float} readOnly="readOnly"></textarea>
                </div>
                <div style={{display: `${isSrcShow}`}}>
                    <textarea rows='8' cols='40' value={this.state.ansr} readOnly="readOnly"></textarea>
                </div>
                <div style={{display: `${isTextShow}`}}>
                    <textarea rows='8' cols='40' value={this.state.ansr_text} readOnly="readOnly"></textarea>
                </div>
            </div>
            <div style={{display: `${isQueryShow}`}}>
                <table>
                <tbody>
                <tr>
                <td>式子：</td>
                <td>
                    <input
                        value={this.state.query_expr}
                        onChange={this.set_query_expr}
                        type="text" size="10" maxLength="200"></input>
                </td>
                <td>求解变量：</td>
                <td>
                    <input
                        value={this.state.query_unns}
                        onChange={this.set_query_unns}
                        type="text" size="5" maxLength="12"></input>
                </td>
                <td>LaTeX：</td>
                <td>
                    <input
                        value={this.state.query_latex}
                        onChange={this.set_query_latex}
                        type="text" size="10" maxLength="200"></input>
                </td>
                <td>src：</td>
                <td>
                    <input
                        value={this.state.query_text}
                        onChange={this.set_query_text}
                        type="text" size="10" maxLength="200"></input>
                </td>
                </tr>
                </tbody>
                </table>
                <table>
                <tbody>
                <tr>
                <td>近似值：</td>
                <td>
                    <input
                        value={this.state.query_float}
                        onChange={this.set_query_float}
                        type="text" size="10" maxLength="200"></input>
                </td>
                <td>开始时间：</td>
                <td>
                <TheDateTime defaultDateTime={this.state.query_begin_time} setDateTime={this.set_begin_time}/>
                </td>
                <td>结束时间：</td>
                <td>
                <TheDateTime defaultDateTime={this.state.query_end_time} setDateTime={this.set_end_time}/>
                </td>
                </tr>
                </tbody>
                </table>
                <Table
                    head={this.state.thead}
                    data={this.state.tdata}
                    queryData={this.queryCalcRecord}
                    deleteData={this.batchDelCalcRecord}
                    modifyData={this.modifyCalcRecord}
                    recordCount={this.state.record_count}
                    recordHits={this.state.record_hits}
                    restartQuery = {this.state.restart_query} />
            </div>
            </div>
        );
    }
}

export default Math;
